package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.DTO.CartDTO;
import cn.edu.tju.elm.model.entity.Cart;
import cn.edu.tju.elm.common.response.HttpResult;
import cn.edu.tju.elm.service.CartService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "购物车管理", description = "提供购物车商品的增删改查功能，包括添加商品、修改数量、按商家查询等")
public class CartController {
    private final CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    @Operation(
            summary = "添加商品到购物车",
            description = "将指定商品添加到当前用户的购物车中，如果商品已存在则更新数量"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "商品或商家不存在")
    })
    @PostMapping("/carts")
    public HttpResult<Cart> addCartItem(
            @Parameter(description = "购物车商品信息", required = true)
            @RequestBody Cart cart){
        return HttpResult.ok(cartService.addCart(cart));
    }

    @PatchMapping("/carts")
    @Operation(
            summary = "更新购物车商品数量",
            description = "更新购物车中指定商品的数量，只能更新当前用户购物车中的商品"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "403", description = "只能修改自己的购物车"),
            @ApiResponse(responseCode = "404", description = "购物车商品不存在")
    })
    public HttpResult<Cart> patchCart(
            @Parameter(description = "购物车商品更新信息", required = true)
            @RequestBody CartDTO cartDTO){
        return HttpResult.ok(cartService.patchCartQuantity(cartDTO));
    }

    @GetMapping("/carts")
    @Operation(
            summary = "获取指定商家的购物车商品",
            description = "根据商家ID获取当前用户在该商家的所有购物车商品列表"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "商家不存在")
    })
    public HttpResult<List<Cart>> findCartByBusiness(
            @Parameter(
                    description = "商家ID",
                    required = true,
                    example = "1",
                    schema = @Schema(type = "integer", format = "int64")
            )
            @RequestParam Long businessId){
        return HttpResult.ok(cartService.findCartByBusiness(businessId));
    }
}